import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useNavigate } from 'react-router-dom'

const API_BASE_URL = 'http://localhost:5000/api'

export default function LoginPage() {
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [nickname, setNickname] = useState('')
  const [step, setStep] = useState('phone') // 'phone' | 'verify'
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const navigate = useNavigate()

  const sendCode = async () => {
    if (!phone) {
      setError('请输入手机号')
      return
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch(`${API_BASE_URL}/auth/send-code`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone }),
      })

      const data = await response.json()

      if (response.ok) {
        setStep('verify')
        // 在开发环境中显示验证码
        if (data.code) {
          setError(`验证码已发送: ${data.code}`)
        }
      } else {
        setError(data.error || '发送验证码失败')
      }
    } catch (err) {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  const login = async () => {
    if (!code) {
      setError('请输入验证码')
      return
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch(`${API_BASE_URL}/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ phone, code, nickname }),
      })

      const data = await response.json()

      if (response.ok) {
        // 保存用户信息到localStorage
        localStorage.setItem('user', JSON.stringify(data.user))
        navigate('/circles')
      } else {
        setError(data.error || '登录失败')
      }
    } catch (err) {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen walker-gradient flex items-center justify-center p-4">
      <div className="bg-white rounded-lg shadow-lg p-8 w-full max-w-md">
        {/* 头部 */}
        <div className="text-center mb-8">
          <div className="w-16 h-16 bg-walker-orange rounded-full flex items-center justify-center mx-auto mb-4">
            <span className="text-white text-2xl font-bold">W</span>
          </div>
          <h1 className="text-2xl font-bold walker-green">WalkerRadio</h1>
          <p className="text-gray-600 mt-2">户外电波 - 与伙伴分享旅程</p>
        </div>

        {/* 表单 */}
        <div className="space-y-4">
          {step === 'phone' ? (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  手机号
                </label>
                <Input
                  type="tel"
                  placeholder="请输入手机号"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="w-full"
                />
              </div>
              <Button 
                onClick={sendCode} 
                className="w-full bg-walker-orange hover:bg-walker-orange/90"
                disabled={loading}
              >
                {loading ? '发送中...' : '获取验证码'}
              </Button>
            </>
          ) : (
            <>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  验证码
                </label>
                <Input
                  type="text"
                  placeholder="请输入验证码"
                  value={code}
                  onChange={(e) => setCode(e.target.value)}
                  className="w-full"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  昵称（可选）
                </label>
                <Input
                  type="text"
                  placeholder="请输入昵称"
                  value={nickname}
                  onChange={(e) => setNickname(e.target.value)}
                  className="w-full"
                />
              </div>
              <Button 
                onClick={login} 
                className="w-full bg-walker-orange hover:bg-walker-orange/90"
                disabled={loading}
              >
                {loading ? '登录中...' : '登录/注册'}
              </Button>
              <Button 
                variant="outline" 
                onClick={() => setStep('phone')}
                className="w-full"
              >
                返回
              </Button>
            </>
          )}
          
          {error && (
            <div className={`text-sm text-center p-3 rounded-md ${
              error.includes('验证码已发送') 
                ? 'text-green-600 bg-green-50 border border-green-200' 
                : 'text-red-600 bg-red-50 border border-red-200'
            }`}>
              {error}
            </div>
          )}
          
          <div className="text-xs text-gray-500 text-center mt-6">
            首次使用将自动注册
          </div>
          
          <div className="flex justify-center space-x-4 text-xs text-gray-500 mt-4">
            <a href="#" className="hover:underline">《隐私政策》</a>
            <a href="#" className="hover:underline">《服务条款》</a>
          </div>
        </div>
      </div>
    </div>
  )
}

